import moment from 'moment'
import _ from 'lodash'
import Big from 'big.js'
/**
 * 生产报表导出xlsx
 * @param data 待导出数据
 * @param visibleColumns 显示列
 * @param columnsName 列名
 * @returns {{tableData: [导出xlsx数据（合并处预留null占位）], merges: [{s: {r: 起始行数, c: 起始列数}, e: {r: 终止行数, c: 终止列数}}]}}
 * https://github.com/SheetJS/sheetjs
 */
function getSheetData (data, visibleColumns, columnsName) {
  let tableData = [
    []
  ]
  let merges = []
  visibleColumns.forEach(item => {
    tableData[0].push(columnsName[item])
  })
  data.forEach((order, index) => {
    const startRows = tableData.length
    order.products.forEach((product, productIndex) => {
      const startRows = tableData.length
      product.processPlannings.forEach((sort, sortIndex) => {
        let item = []
        const count = {
          planningCount: _.isNil(sort.planningCount) ? 0 : Number(sort.planningCount),
          defectiveCount: _.isNil(sort.defectiveCount) ? 0 : Number(sort.defectiveCount),
          actualCount: _.isNil(sort.actualCount) ? 0 : Number(sort.actualCount),
          compromiseCount: _.isNil(sort.compromiseCount) ? 0 : Number(sort.compromiseCount)
        }
        visibleColumns.forEach(columns => {
          switch (columns) {
            case 'indexId':
              // item.push(productIndex === 0 && sortIndex === 0 ? index + 1 : null)
              if (productIndex === 0 && sortIndex === 0) {
                item.push(index + 1)
              } else {
                item.push(null)
              }
              break
            case 'orderNumber':
              item.push(productIndex === 0 && sortIndex === 0 ? (_.isNil(order.orderNumber) ? '--' : order.orderNumber) : null)
              break
            case 'orderBatch':
            case 'productNumber':
            case 'productName':
              item.push(sortIndex === 0 ? (_.isNil(product[columns]) ? '--' : product[columns]) : null)
              break
            case 'processName':
              item.push(`${sortIndex + 1} - ${_.isNil(sort.processName) ? '--' : sort.processName}`)
              break
            case 'planningStartTime':
            case 'planningEndTime':
            case 'actualStartTime':
            case 'actualEndTime':
              item.push(`${_.isNil(sort[columns]) ? '--' : moment(sort[columns]).format('YYYY-MM-DD HH:mm:ss')}`)
              break
            case 'planningCount':
            case 'actualCount':
            case 'defectiveCount':
            case 'compromiseCount':
              item.push(count[columns])
              break
            case 'reachRate':
              item.push(`${count.planningCount === 0 ? '0.00' : (count.actualCount / count.planningCount * 100).toFixed(2)}%`)
              break
            case 'throughRate':
              item.push(`${count.actualCount === 0 ? '0.00' : ((count.actualCount - count.defectiveCount - count.compromiseCount) / count.actualCount * 100).toFixed(2)}%`)
              break
            case 'badRate':
              item.push(`${count.actualCount === 0 ? '0.00' : ((count.defectiveCount) / count.actualCount * 100).toFixed(2)}%`)
              break
            case 'passRate':
              item.push(`${count.actualCount === 0 ? '0.00' : ((count.actualCount - count.defectiveCount) / count.actualCount * 100).toFixed(2)}%`)
              break
          }
        })
        tableData.push(item)
      })
      const endRows = tableData.length
      // 产品合并格
      for (let i = 1; i <= 4; i++) {
        merges.push({
          s: { r: startRows, c: i },
          e: { r: endRows - 1, c: i }
        })
      }
    })
    const endRows = tableData.length
    // 序号列
    merges.push({
      s: { r: startRows, c: 0 },
      e: { r: endRows - 1, c: 0 }
    })
    // 订单号列
    merges.push({
      s: { r: startRows, c: 1 },
      e: { r: endRows - 1, c: 1 }
    })
  })
  return { tableData, merges }
}
function getDeviceRateSheetData (data, visibleColumns) {
  let tableData = [
    ['设备']
  ]
  let merges = []
  // 处理表头
  visibleColumns.forEach(item => {
    const start = tableData[0].length
    tableData[0] = tableData[0].concat([item, null, null, null])
    const end = tableData[0].length - 1
    merges.push({
      s: { r: 0, c: start },
      e: { r: 0, c: end }
    })
  })
  data.forEach(item => {
    console.log(item, '  item')

    let first = []
    let second = [null]
    let third = [null]
    let fourth = [null]
    let fifth = [null]
    let sixth = [null]
    let seventh = [null]
    item.tr.forEach((cell, index) => {
      const start = first.length
      if (index) {
        // const firstStart = first.length
        first = first.concat(['时间开动率(A)', `${getPercentage(cell.availability)}%`, '计划开机时长', `${getDuration(cell.planTime)}`])
        second = second.concat([null, null, '实际加工时长', `${getDuration(cell.actualTime)}`])
        third = third.concat(['性能开动率(P)', `${getPercentage(cell.performance)}%`, '理论节拍合计', `${getDuration(cell.academicBeat)}`])
        fourth = fourth.concat([null, null, '实际节拍合计', `${getDuration(cell.actualBeat)}`])
        fifth = fifth.concat(['合格率(Q)', `${getPercentage(cell.quality)}%`, '完工数量', cell.actualCount])
        sixth = sixth.concat([null, null, '不良数量', cell.badCount])
        seventh = seventh.concat(['设备稼动率（OEE）', `${getPercentage(cell.oee)}%`, null, null])
        // 时间开动率(A)
        merges.push({
          s: { r: tableData.length, c: start },
          e: { r: tableData.length + 1, c: start }
        })
        // 时间开动率(A)值
        merges.push({
          s: { r: tableData.length, c: start + 1 },
          e: { r: tableData.length + 1, c: start + 1 }
        })
        // 性能开动率(P)
        merges.push({
          s: { r: tableData.length + 2, c: start },
          e: { r: tableData.length + 3, c: start }
        })
        // 性能开动率(P)值
        merges.push({
          s: { r: tableData.length + 2, c: start + 1 },
          e: { r: tableData.length + 3, c: start + 1 }
        })
        // 合格率(Q)
        merges.push({
          s: { r: tableData.length + 4, c: start },
          e: { r: tableData.length + 5, c: start }
        })
        // 合格率(Q)值
        merges.push({
          s: { r: tableData.length + 4, c: start + 1 },
          e: { r: tableData.length + 5, c: start + 1 }
        })
        // 设备稼动率（OEE）值
        merges.push({
          s: { r: tableData.length + 6, c: start + 1 },
          e: { r: tableData.length + 6, c: start + 3 }
        })
      } else {
        // 设备
        first.push(`${item.tr[0].deviceName}`)
        merges.push({
          s: { r: tableData.length, c: 0 },
          e: { r: tableData.length + 6, c: 0 }
        })
      }
    })

    tableData = tableData.concat([first, second, third, fourth, fifth, sixth, seventh])
  })
  console.log(tableData)
  return { tableData, merges }
}
/**
 * 常规表格导出数据 （可筛选列）
 * @param data 待导出数据
 * @param visibleColumns 显示列
 * @param columnsName 列名map（{name，label}）
 * @returns {[[]]} Excel数据
 */
function exportExcel (data, visibleColumns, columnsName) {
  let tableData = [
    []
  ]
  visibleColumns.forEach(item => {
    tableData[0].push(columnsName[item])
  })
  data.forEach((cell, index) => {
    let item = []
    visibleColumns.forEach(columns => {
      item.push(cell)
    })
    tableData.push(item)
  })
  return tableData
}

/**
 * 秒转时分秒
 * @param second 秒
 * @returns {string} 时分秒
 */
function getDuration (second) {
  if (!second) {
    return '0秒'
  }
  let isNegative = false
  if (second < 0) {
    isNegative = true
    second = new Big(second).abs()
  } else {
    second = new Big(second)
  }
  const hours = Math.floor(second.div(3600).toFixed(10))
  const minutes = Math.floor(second.mod(3600).div(60).toFixed(10))
  const seconds = second.mod(3600).mod(60).toFixed(0)
  var duration = getCovering(hours, '小时') + getCovering(minutes, '分') + getCovering(seconds, '秒')
  duration !== '' && isNegative && (duration = '-' + duration)
  return duration
}

function getCovering (num, label = '', isNull = '') {
  if (num && num > 0) {
    // num < 10 && (num = `0${num}`)
    return `${num}${label}`
  } else {
    return isNull
  }
}
/**
 * 获取百分比
 * @param val
 * @returns {string | *} 百分比数
 */
function getPercentage (val) {
  return (_.isNil(val) ? 0 : val * 100).toFixed(2)
}

export default {
  getSheetData,
  getDeviceRateSheetData,
  getDuration,
  getPercentage,
  exportExcel
}
